<template>
  <div>
    <el-drawer
        :title="title"
        v-model="drawer"
        size="87%"
        :direction="direction"
        :before-close="handleClose">
      <div style="width: 100%; height: 100%;text-align:left;background-color:white;" id="propertiesFLag">

        <el-row style="width:100%">
          <el-col :span="22">
            <el-row>
              <el-col :span="2.5">版本：</el-col>
              <el-col :span="6">


                <el-select v-model="this.currentVersion" @change="this.change" class="m-2" placeholder="Select"
                           size="large">
                  <el-option
                      v-for="item in this.versionList"
                      :key="item.version"
                      :label="item.label"
                      :value="item.id"
                  />
                </el-select>

              </el-col>

              <el-col :span="6">


                <el-select v-model="this.logLevel" class="m-2" placeholder="Select"
                           size="large">
                  <el-option
                      v-for="item in this.logLevelList"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                  />
                </el-select>

              </el-col>


              <el-col :span="2">
                调试
                <el-switch
                    v-model="localFrontDebug"
                    class="ml-2"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                />
              </el-col>

              <el-col :span="4">
                <el-input v-model="debugUrl" placeholder="请输入地址" @change="debugUrlChange"
                          v-show="localFrontDebug"/>

              </el-col>

              <el-col :span="4">
                <Button type="primary" @click="compnentTest">测试</Button>


                <el-dialog v-model="stepTestFlag" title="请输入参数">
                  <div class="jsoneditor" ref="jsonEditor" style="width: 100%; height: 600px;"></div>
                  <template #footer>
                    <span class="dialog-footer">
                      <el-button @click="stepTestFlag = false">取消</el-button>
                      <el-button type="primary" @click="stepTest">
                        提交
                      </el-button>
                    </span>
                  </template>
                </el-dialog>
              </el-col>

            </el-row>

          </el-col>
          <el-col :span="2">
            <div id="lvvss" style="position: absolute;z-index: 9990;">
                 <span @click="this.maxProperties">
              <svg t="1671007574107" class="icon" viewBox="0 0 1024 1024" version="1.1"
                   xmlns="http://www.w3.org/2000/svg" p-id="3914" data-spm-anchor-id="a313x.7781069.0.i3" width="20"
                   height="20"><path
                  d="M919.920093 725.414549q3.014188 26.122962 7.033105 58.776664t7.53547 66.814498 7.53547 67.819227 7.033105 60.786122q6.028376 47.222277-41.193901 44.208089-25.118232-2.009459-56.767205-5.526011t-64.805039-7.53547-65.809769-8.037834-59.781393-7.033105q-29.137149-3.014188-37.174984-16.578033t9.042564-30.644243q11.052022-10.047293 27.127691-27.630056t27.127691-28.634785q11.052022-12.056752 7.033105-22.104044t-16.075669-23.108774q-28.13242-27.127691-51.241194-49.231735t-51.241194-51.241194q-6.028376-6.028376-12.056752-13.061481t-9.042564-15.573304-1.004729-18.085127 13.061481-20.59695q6.028376-6.028376 10.047293-10.549658t8.037834-8.037834 8.540199-8.037834 11.554387-12.559116q20.094586-20.094586 37.174984-17.080398t37.174984 23.108774 41.193901 40.691536 47.222277 46.719912q19.089857 18.085127 32.653702 25.118232t26.625326-6.028376q9.042564-9.042564 22.606409-21.60168t23.611138-22.606409q17.080398-17.080398 30.644243-13.061481t16.578033 30.141879zM43.79615 383.80659q-3.014188-26.122962-7.033105-58.776664t-7.53547-66.814498-7.53547-67.819227-7.033105-60.786122q-3.014188-26.122962 6.53074-36.170255t33.658431-8.037834q25.118232 2.009459 56.767205 5.526011t64.805039 7.53547 65.809769 8.037834 59.781393 7.033105q30.141879 3.014188 37.677348 16.578033t-9.544928 30.644243q-10.047293 10.047293-24.615868 26.122962t-25.620597 27.127691q-12.056752 12.056752-8.037834 22.104044t17.080398 23.108774q13.061481 14.06621 24.615868 24.615868t22.606409 21.099315 23.108774 22.606409l25.118232 25.118232q6.028376 6.028376 11.554387 14.06621t8.037834 17.080398-0.502365 19.089857-13.061481 20.094586l-11.052022 11.052022q-4.018917 4.018917-7.53547 8.037834t-8.540199 8.037834l-11.052022 12.056752q-20.094586 20.094586-34.663161 15.070939t-34.663161-25.118232-38.179713-37.677348-44.208089-43.705724q-18.085127-18.085127-32.151337-25.118232t-27.127691 6.028376q-9.042564 10.047293-25.118232 24.615868t-26.122962 24.615868q-17.080398 17.080398-30.141879 13.061481t-16.075669-30.141879zM905.853883 84.397261q26.122962-3.014188 36.170255 6.53074t8.037834 34.663161-5.526011 56.767205-7.53547 64.805039-8.037834 65.809769-7.033105 59.781393q-3.014188 29.137149-16.578033 37.174984t-30.644243-10.047293q-10.047293-10.047293-26.122962-24.615868t-27.127691-25.620597q-12.056752-11.052022-22.104044-7.53547t-23.108774 16.578033q-27.127691 27.127691-47.724641 49.231735t-48.729371 50.236465q-6.028376 6.028376-14.06621 11.554387t-17.080398 8.037834-19.089857-0.502365-20.094586-14.06621q-6.028376-6.028376-10.549658-10.047293t-8.540199-8.037834-8.540199-8.037834-11.554387-12.056752q-20.094586-20.094586-16.075669-35.165525t25.118232-35.165525l38.179713-40.189172q19.089857-20.094586 45.212818-46.217547 19.089857-18.085127 26.122962-32.151337t-7.033105-26.122962q-9.042564-9.042564-23.108774-24.615868t-24.113503-25.620597q-17.080398-17.080398-13.061481-30.141879t30.141879-16.075669 58.776664-7.033105 67.316863-7.53547 67.819227-7.53547 60.283758-7.033105zM350.238584 640.012559q6.028376 6.028376 10.549658 10.047293t8.540199 8.037834l8.037834 9.042564 12.056752 11.052022q20.094586 20.094586 17.582763 36.672619t-23.611138 37.677348q-19.089857 19.089857-40.189172 40.691536t-47.222277 47.724641q-18.085127 18.085127-22.606409 29.639514t8.540199 24.615868q10.047293 9.042564 22.606409 22.606409t22.606409 23.611138q17.080398 17.080398 12.559116 30.141879t-30.644243 16.075669-58.274299 7.033105-66.814498 8.037834-68.321592 8.037834-60.786122 7.033105q-25.118232 2.009459-35.66789-7.53547t-8.540199-33.658431q2.009459-25.118232 5.526011-56.767205t7.53547-64.805039 8.037834-65.809769 7.033105-59.781393q3.014188-30.141879 16.578033-37.677348t30.644243 9.544928q10.047293 10.047293 27.630056 26.122962t28.634785 27.127691q12.056752 12.056752 20.094586 10.549658t20.094586-14.568575q13.061481-13.061481 25.118232-25.620597t24.113503-24.615868 24.615868-25.118232 26.625326-27.127691q6.028376-6.028376 13.061481-12.056752t15.573304-9.042564 18.085127-0.502365 20.59695 13.563845z"
                  p-id="3915" fill="#dbdbdb"></path></svg>
                 </span>
            </div>
          </el-col>
        </el-row>
        <el-row style="height: 100%">
          <el-col :span="24">
            <div class="grid-content" style="height: 100%;width:100%;">
              <div class="container" id="container" ref="ct">
              </div>
              <div class="container" id="componentContainer">
                <component v-if="dynamicCode" :is="dynamicCode" :input="this.componentInputData"
                           :output="this.componentOutputData"></component>
              </div>

            </div>
          </el-col>
        </el-row>
      </div>
    </el-drawer>
  </div>
</template>

<script>
// import {jquery} from "./SquareLakeFlowJquery.js";

import {get, getBaseUrl, post} from "@/config/Request.js";
import {ElLoading} from "element-plus";
import {toRaw} from "vue";
import {Button} from "view-ui-plus";
import JsonEditor from 'jsoneditor';
import 'jsoneditor/dist/jsoneditor.min.css';
import apis from "@/request/apis.js";

export default {
  name: 'SquareLakeFlowBizProperties',
  components: {Button},
  props: {
    propertiesBackFill: Function,
    getProcessVersionId: Function,
    getResource: Function,
    parseDefineToJson: Function,
    getNodeProperties: Function
  },

  data() {
    return {
      isMaximum: false,
      drawer: false,
      direction: 'rtl',
      versionList: [],
      currentVersion: null,
      logLevelList: [],
      logLevel: "",
      dynamicCode: null,
      name: "",
      componentInputData: null,
      componentOutputData: null,
      title: "",
      data: null,
      localFrontDebug: false,
      debugUrl: "",
      activeFrameId: "",
      activeFrameCode: null,
      je: null,
      activeFrameData: null,
      stepTestFlag: null,
      whileGetDataFlag: false
    };
  },
  mounted() {
    this.message();
  },
  methods: {
    async getCurrentInputDefine() {
      const versionId = this.getProcessVersionId();
      const resource = this.getResource();
      //需要调用后端查询接口定义
      const read = await apis.post("/square-lake/process/version/content/get_current_input_define", {
        id: versionId,
        processId: null,
        processVersion: this.currentVersion,
        resource: resource,
        stepCode: this.activeFrameId
      });
      return read;
    },
    initJsonEditor() {
      const options = {
        "modes": ["code", "tree", "form", "text", "preview"],
        "mode": "code"
      }
      this.je = new JsonEditor(this.$refs.jsonEditor, options);

      // this.je.setMode("tree");
      // this.je.setMode("code");
      // this.je.update(「」);
      this.updateTestJson();
    },
    async updateTestJson() {
      const obj = await this.getCurrentInputDefine();
      let define = this.parseDefineToJson(obj);
      if (!define) {
        define = {
          "": ""
        };
      }
      this.je.update(define);
    },
    compnentTest() {
      //手动保存一把先，保存完了在调用后端测试
      this.valueProcessor(async function () {
        //弹窗输入参数
        this.stepTestFlag = true;
        if (!this.je) {
          setTimeout(() => this.initJsonEditor(), 0);
        } else {
          await this.updateTestJson();
        }

      }.bind(this));

    },
    async stepTest() {


      //获取一把tid
      const tid = await apis.post("/square-lake/process/test/get_tid", null);

      //获取xml
      const versionId = this.getProcessVersionId();
      const resource = this.getResource();

      const value = this.je.get();
      const obj = await apis.post("/square-lake/process/test/step/run", {
        id: versionId,
        processId: null,
        processVersion: this.currentVersion,
        resource: resource,
        param: value,
        stepCode: this.activeFrameId,
        tid: tid
      });
      this.$message.info("执行成功，结果=>" + JSON.stringify(obj));


      //    this.stepTestFlag = false;
    },
    handleClose(done) {
      //   this.$confirm('确认关闭？')
      //    .then(() => {
      this.valueProcessor(function () {
        this.activeFrameData = null;
        this.activeFrameId = null;
        this.name = null;
        this.componentInputData = null;
        this.componentOutputData = null;
        this.dynamicCode = null;
        this.currentVersion = null;
        done();
      }.bind(this));
      this.drawer = false;
      // })
      // .catch(() => {
      // });
    },
    async queryLogLevelList() {
      const data = await apis.post("/square-lake/process/log_level_list", {});
      this.logLevelList = data;
    },
    maxProperties() {
      if (this.isMaximum) {
        this.min();
      } else {
        this.max();
      }

    },
    min() {
      this.isMaximum = false
      let dom = document.getElementById("propertiesFLag")
      dom.style.zIndex = "";

      dom.classList.remove('editor-fullscreen')
      let maxIcon = document.getElementById("lvvss");
      maxIcon.style.right = ""
      maxIcon.style.top = "";
      // toRaw(this.monacoEditor).layout({
      //   height: this.originSize.height,
      //   width: this.originSize.width
      // })
    },
    debugUrlChange() {
      document.getElementById('fm-' + this.activeFrameId).remove();
      this.createIframe();
    },
    max() {
      this.isMaximum = true
      let dom = document.getElementById("propertiesFLag")
      dom.style.zIndex = "9999";
      this.originSize = {
        width: dom.clientWidth,
        height: dom.clientHeight
      }
      dom.classList.add('editor-fullscreen');
      let maxIcon = document.getElementById("lvvss");
      maxIcon.style.right = "20px"
      maxIcon.style.top = "30px";
      // toRaw(this.monacoEditor).layout({
      //   height: document.body.clientHeight,
      //   width: document.body.clientWidth
      // })
    },
    valueProcessor(done) {
      let iframe = document.getElementById('fm-' + this.activeFrameId);
      if (iframe) {
        iframe.contentWindow.postMessage(JSON.stringify({
          type: "getData"
        }), "*");
        this.whileGetDataFlag = true;
        this.whileGetData(function () {
          this.versionList.forEach(v => {
            if (v.version == this.currentVersion) {
              this.activeFrameData.pluginId = v.id;
            }
          });
          this.activeFrameData.version = this.currentVersion;
          this.activeFrameData.logLevel = this.logLevel;
          this.propertiesBackFill(this.activeFrameId, this.activeFrameData);

          if (done) {
            done();
          }
        }.bind(this));
      } else {
        this.activeFrameData = this.componentOutputData;
        this.versionList.forEach(v => {
          if (v.version == this.currentVersion) {
            this.activeFrameData.pluginId = v.id;
          }
        });
        this.activeFrameData.version = this.currentVersion;
        this.activeFrameData.logLevel = this.logLevel;
        this.propertiesBackFill(this.activeFrameId, this.activeFrameData);
        if (done) {
          done();
        }
      }
    },
    whileGetData(callback) {
      if (this.whileGetDataFlag) {
        if (this.activeFrameData != null) {
          this.whileGetDataFlag = false;
          callback();
          return;
        } else {
          setTimeout(function () {
            this.whileGetData(callback);
          }.bind(this), 0)
        }
      }
    },
    async show(code, id, name, data) {
      if (!data) {
        data = {};
      }
      if (!code) {
        return;
      }
      await this.queryVersionList(code);
      await this.queryLogLevelList();
      var version = data.version;
      if (null == version) {
        version = this.versionList[0].version;
      }
      if (data.logLevel) {
        this.logLevel = data.logLevel;
      }
      this.localFrontDebug = false;
      this.debugUrl = "";
      this.currentVersion = version;
      this.drawer = true;
      this.name = name;
      this.title = name + "(" + id + ")";
      this.activeFrameId = id;
      this.activeFrameCode = code;
      this.data = data;

      console.log(code);

      setTimeout(() => {
        this.createIframe();
      }, 0);

      // let iwindow = iframe.contentWindow; // 获取iframe的window对象
      // let idoc = iframe.contentDocument; // 获取iframe的document对象


      // this.$refs.container
      //这里要动态创建iframe

    },
    async createIframe() {

      //创建iframe
      //先把下面的所有iframe隐藏起来
      var element = document.querySelector("#container");
      var childNodes = element.childNodes;
      if (childNodes && childNodes.length > 0) {
        childNodes.forEach(v => {
          v.style.display = "none";
        })
      }

      let iframe = document.getElementById('fm-' + this.activeFrameId);
      if (iframe) {
        iframe.style.display = "block";
        const data = {...this.data}
        data.versionId = this.getProcessVersionId();
        data.resource = this.getResource();
        data.processVersion = this.currentVersion;
        data.stepCode = this.activeFrameId;

        iframe.contentWindow.postMessage(JSON.stringify({
          type: "setData",
          data: data
        }), "*");

      } else {
        const s = document.querySelector("#container");
        //创建一把
        iframe = document.createElement('iframe');
        iframe.name = "fm-" + this.activeFrameId;
        iframe.id = "fm-" + this.activeFrameId;
        iframe.frameBorder = "0";
        iframe.allow = "fullscreen";
        iframe.width = "100%";
        if (!s.offsetHeight) {
          iframe.height = s.parentElement.offsetHeight;
        } else {
          iframe.height = s.offsetHeight;
        }

        const host = `http://${getBaseUrl()}`;

        var elLoadingComponent = ElLoading.service({
          target: s,
          lock: true, text: '加载中', spinner: 'el-icon-loading'
        });
        let v = await apis.get(`/square-lake/component/html?code=${this.activeFrameCode}&version=${this.currentVersion}`, {});

        if (!v) {
          //动态组件
          elLoadingComponent.close();
          await this.appendDynamicComponent();
          return;
        }
        let cs = v.substring(0, v.lastIndexOf("</"));
        let end = v.substring(v.lastIndexOf("</"));
        cs += `<link type='text/javascript' id="css-fm-${this.activeFrameId}" rel="stylesheet" href="${host}/square-lake/component/css?code=${this.activeFrameCode}&version=${this.currentVersion}"/>`;
        // cs += `<script type='text/javascript' id="script-jquery-fm-${id}">${jq}<\/script>`;
        cs += `<script type='text/javascript' id="script-framework-fm-${this.activeFrameId}">
        window.onload = function(){

        if(!window.accessGet){
            console.log("没有找到window.accessGet函数");
        }
                if(!window.accessSet){
            console.log("没有找到window.accessSet函数");
        }
        }
window.editor={
          data:null,
          getData:function(){
              if(window.bindData){
                  this.data = window.bindData;
              }
              if(window.accessGet){
                 this.data =  window.accessGet();
             }
          return this.data;
          },
          setData:function(data){
              if(window.bindData!=null){
                 var keys = Object.keys(data);
                      keys.forEach(v => {
                          window.bindData[v] = data[v];
                      })
              }
                  if(window.accessSet){
                      window.accessSet(data);
                  }
              this.data = data;
          }
          }<\/script>`;
        cs += `<script type='text/javascript' id="script-fm-${this.activeFrameId}" src="${host}/square-lake/component/js?code=${this.activeFrameCode}&version=${this.currentVersion}"><\/script>`

        cs += `<script type='text/javascript' id="script-message-fm-${this.activeFrameId}">window.addEventListener("message", function(event) {
             var d= event.data;
             if(d){
                  var parse = null;
                 if(typeof d =='string'){
                         parse = JSON.parse(d);
                 }else{
                     parse = d;
                 }
                 if(parse&&parse.type=="setData"){
                     window.editor.setData(parse.data);
                 }else if(parse&&parse.type=="getData"){
                     let param = {
                         type:"getData",
                         data:window.editor.getData()
                     }
                     window.parent.postMessage(JSON.stringify(param),"*");
                 }
             }
});<\/script>`

        cs += end;
        const blob = new Blob([cs], {
          type: "text/html"
        });
        let objectURL = window.URL.createObjectURL(blob);
        if (this.localFrontDebug && this.debugUrl) {
          iframe.src = this.debugUrl;
        } else {
          iframe.src = objectURL;
        }

        //     iframe.src = "data:text/html;charset=utf-8," + window.encodeURIComponent(cs);
        s.append(iframe);
        iframe.onload = () => {
          const data = {...this.data}
          data.versionId = this.getProcessVersionId();
          data.resource = this.getResource();
          data.processVersion = this.currentVersion;
          data.stepCode = this.activeFrameId;

          iframe.contentWindow.postMessage(JSON.stringify({type: "setData", data: data}), "*");
          elLoadingComponent.close();
        }
      }
      // window.d = {"user": "name"};
    },
    change(d) {
      let version = "";
      this.versionList.forEach(v => {
        if (v.id == d) {
          version = v.version;
        }
      });
      var s = this.activeFrameId;
      var b = this.name;
      var c = this.activeFrameCode;
      this.activeFrameData = null;
      this.valueProcessor(function () {
        let data = this.getNodeProperties(s);
        //  iframe.remove();
        let iframe = document.getElementById('fm-' + this.activeFrameId);
        if (iframe) {
          iframe.remove();
        }
        data.version = version;
        this.activeFrameData = null;
        this.show(c, s, b, data)
      }.bind(this))

    },
    async appendDynamicComponent() {
      const data = {...this.data}
      data.versionId = this.getProcessVersionId();
      data.resource = this.getResource();
      data.processVersion = this.currentVersion;
      data.stepCode = this.activeFrameId;

      this.componentInputData = data;
      this.componentOutputData = {};
      this.dynamicCode = this.activeFrameCode;

    },
    async queryVersionList(code) {
      const data = await apis.get("/square-lake/component/version_list?code=" + code, {})
      // console.log(data);
      // this.$set(this, "tableData", data);
      this.versionList = data;
    },
    message() {
      window.addEventListener('message', function (e) {  // 监听 message 事件
        const d = e.data;
        if (d && typeof (d) == 'string') {
          let json = {};
          try {
            json = JSON.parse(d);
          } catch (e) {
            console.log("不是一个json")
          }
          if (json.type == "getData") {
            this.activeFrameData = json.data;
          }
        }
      }.bind(this));
    }
  },
  created() {
  }
}
</script>
<style scoped>
/*.container {*/
/*  width: 1000px;*/
/*  height: 500px;*/
/*}*/

.editor-fullscreen {
  position: fixed !important;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100% !important;
  z-index: 1000;
}
</style>
